package com.cw;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JOptionPane;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.cw.action.LotteryAction;
import com.cw.gui.MainPanel;
import com.cw.po.Cpaction;
import com.cw.service.BaseService;
import com.cw.service.CpactionService;

public class Context {

	private static Context instance = new Context();
	private ApplicationContext ac = null;
	private Map<Cpaction, LotteryAction> mapAct = new HashMap<Cpaction, LotteryAction>();
	
	private Context() {
		loadAppContext();
	}
	
	private void loadAppContext(){
		ac = new ClassPathXmlApplicationContext("/applicationContext.xml");
	}
	
	public BaseService getBean(String name) {
		return (BaseService) ac.getBean(name);
	}

	public static Context getInstance(){
		return instance;
	}

	public void loadAction(MainPanel mp){
		CpactionService cpas = (CpactionService) Context.getInstance().getBean("cpactionService");
		List<Cpaction> allcpact = cpas.findAll();
		for(Cpaction act:allcpact){

			String cName = act.getClassName();
			LotteryAction ltAction = null;
			try {
				Class[] arrayOfClass = new Class[3];
				arrayOfClass[0] = MainPanel.class;
				arrayOfClass[1] = String.class;
				arrayOfClass[2] = String.class;
				Object[] arrayOfObject = { mp, act.getName(), act.getAction()};
				Constructor localConstructor = null;
				try {
					localConstructor = Class.forName("com.cw.action."+cName).getConstructor(
							arrayOfClass);
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				}
				try {
					ltAction = (LotteryAction) localConstructor
							.newInstance(arrayOfObject);
				} catch (IllegalArgumentException e) {
					JOptionPane.showMessageDialog(mp,
							"error!Please contract administator!" + cName);
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					JOptionPane.showMessageDialog(mp,
							"error!Please contract administator!" + cName);
				}
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}			
			
			mapAct.put(act, ltAction);
		}		
	}	
	public Map<Cpaction, LotteryAction> getMapActs(){
		return mapAct;
	}
	
}
